﻿namespace ZeroBug.EasyFlow.Core
{
    /// <summary>
    /// 所有机台资源的抽象，包含运控资源，通信资源，等以后可能添加的资源
    /// </summary>
    /// <typeparam name="TResource">资源类型，如Axis</typeparam>
    /// <typeparam name="ROperator">资源实际能力的入口，IAxis，可兼容多个不同品牌</typeparam>
    public class MachineResource<TResource, ROperator> where TResource : class, IMachineResource<ROperator>, new() where ROperator : class
    {
        private LogHelper _logHelper;
        private AssemblyHelper _assemblyHelper;
        public SerializableDictionary<string, TResource>? Value { get; set; }
        public MachineResource(AssemblyHelper assemblyHelper, LogHelper logHelper)
        {
            _assemblyHelper = assemblyHelper;
            _logHelper = logHelper;
            Value = new SerializableDictionary<string, TResource>();
        }
        public void Load(string resourceName)
        {
            Value = XmlSerializerHelper<SerializableDictionary<string, TResource>>.DeserializeFromFile(PathHelper.GetConfigPath("Machine") + $"{resourceName}.xml");
            foreach (KeyValuePair<string, TResource> item in Value)
            {
                item.Value.SetOperator(_assemblyHelper.GetInstance<ROperator>()[item.Value.OperatorName]);
                item.Value.Logger = _logHelper;
            }
        }
        public void Save(string resourceName)
        {
            XmlSerializerHelper<SerializableDictionary<string, TResource>>.SerializeToFile(Value, PathHelper.GetConfigPath("Machine") + $"{resourceName}.xml");
        }
    }
}
